<template>
  <el-dialog
    :close-on-click-modal="false"
    title="劳务合同"
    :visible.sync="show"
    width="1000px"
    center
  >
    <el-form ref="form" :rules="rules" style="padding-top: 10px;" :model="form" label-width="120px">
      <div class="com-form-title">基础信息</div>
      <el-row>
        <!-- <el-col :span="8">
          <el-form-item label="项目名称" prop="projectName">
            <el-input v-model="form.projectName" readonly :disabled="disableForm || optType !== 'add'" @click.native="optType === 'add' ? showTargetSetListModal = true : null">
              <i slot="suffix" class="el-input__icon el-icon-circle-plus-outline" />
            </el-input>
          </el-form-item>
        </el-col> -->
        <el-col :span="8">
          <el-form-item label="部门名称" prop="departmentName">
            <el-input v-model="form.departmentName" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="乙方名称" prop="employeeName">
            <!-- <el-input v-model="form.employeeName" readonly :disabled="disableForm || optType !== 'add'" @click.native="optType === 'add' ? showTeamListModal = true : null">
              <i slot="suffix" class="el-input__icon el-icon-circle-plus-outline" />-->
            <el-input v-model="form.employeeName" :disabled="disableForm || optType !== 'add'">
              <i slot="suffix" class="el-input__icon el-icon-circle-plus-outline" @click="optType === 'add' ? showTeamListModal = true : null" />
            </el-input>
            <!-- <el-input v-model="form.teamNumber" :disabled="disableForm" /> -->
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="分包队伍编号" prop="teamNumber">
            <el-input v-model="form.teamNumber" :disabled="true" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="甲方名称" prop="employerName">
            <el-input v-model="form.employerName" :disabled="disableForm" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="劳务合同编号" prop="contractNumber">
            <el-input v-model="form.contractNumber" placeholder="自动生成" :disabled="true" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="劳务合同名称" prop="contractName">
            <el-input v-model="form.contractName" :disabled="disableForm" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="初始合同金额(元)" prop="initAmount">
            <el-input v-model="form.initAmount" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="签订时间" prop="signTime">
            <el-date-picker v-model="form.signTime" style="width:100%" type="date" :disabled="disableForm" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="描述" prop="description">
            <el-input v-model="form.description" :disabled="disableForm" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="备注" prop="remark">
            <el-input v-model="form.remark" :disabled="disableForm" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label-width="150px" label="电子版合同是否上传" prop="elecContractUpload">
            <el-select v-model="form.elecContractUpload" :disabled="disableForm" style="width: 100%;" placeholder="请选择电子版合同是否上传">
              <el-option v-for="item in transferContractInfoElecContractUpload" :key="item.name" :label="item.name" :value="item.value" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label-width="150px" label="纸质版合同是否上传" prop="paperContractUpload">
            <el-select v-model="form.paperContractUpload" :disabled="disableForm" style="width: 100%;" placeholder="请选择纸质版合同是否上传">
              <el-option v-for="item in transferContractInfoPaperContractUpload" :key="item.name" :label="item.name" :value="item.value" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <div class="btns" style="padding-bottom: 10px;">
        <el-button type="primary" @click="addRow">新增行</el-button>
        <el-button type="primary" @click="delDetailDataItem">删除行</el-button>
      </div>
      <com-table
        v-model="selectRow"
        :no-page="true"
        :columns="columns"
        highlight-current-row
        :data="detailDataList"
      >
        <template v-slot:number="{row}">
          <el-input v-model="row.number" />
        </template>
        <template v-slot:name="{row}">
          <el-input v-model="row.name" />
        </template>
        <template v-slot:unit="{row}">
          <el-input v-model="row.unit" />
        </template>
        <template v-slot:taxRate="{row}">
          <el-input v-model="row.taxRate" />
        </template>
        <template v-slot:taxes="{row}">
          <el-input v-model="row.taxes" />
        </template>
        <template v-slot:unitPrice="{row}">
          <el-input v-model="row.unitPrice" @input="inputUnitPrice" />
        </template>
        <template v-slot:sumPrice="{row}">
          <el-input v-model="row.sumPrice" />
        </template>
        <template v-slot:count="{row}">
          <el-input v-model="row.count" @input="inputCount" />
        </template>
        <template v-slot:description="{row}">
          <el-input v-model="row.description" />
        </template>
        <template v-slot:remark="{row}">
          <el-input v-model="row.remark" />
        </template>
      </com-table>
      <el-button style="margin-top:10px;" type="primary" @click="showFileModal = true">附件资料({{ fileList.length }})</el-button>
      <file-uploader v-model="fileList" :show-modal.sync="showFileModal" :disabled="disableForm" :can-download="optType==='detail'" />

    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="show = false">取 消</el-button>
      <el-button type="primary" @click="saveDoc">确 定</el-button>
    </span>
    <project-list :show-modal.sync="showTargetSetListModal" @getSelectedRows="getSelectedRows" />
    <team-list :show-modal.sync="showTeamListModal" @getSelectedRows="getSelectedRowsTeam" />
  </el-dialog>
</template>

<script>
import { addTransferContractInfo, updateTransferContractInfo, getTransferContractInfoDetail } from '@/api/runManage'
import { getAreaList } from '@/api/common'
import { transferContractInfoElecContractUpload, transferContractInfoPaperContractUpload, workflowStatus } from '@/utils/dicData'
import fileUploader from '@/components/FileUploader'
import ProjectList from '@/components/TreeModal/project'
import TeamList from '@/components/TreeModal/team'
export default {
  name: 'AddTransferContractInfo',
  components: {
    fileUploader,
    ProjectList,
    TeamList
  },
  props: {
    showModal: {
      type: Boolean,
      default: false
    },
    optType: {
      type: String,
      default: 'add'
    },
    dir: {
      type: Object,
      default() {
        return {}
      }
    },
    data: {
      type: Object,
      default() {
        return {}
      }
    }
  },
  data() {
    return {
      showFileModal: false,
      targetList: [],
      transferContractInfoElecContractUpload,
      transferContractInfoPaperContractUpload,
      workflowStatus,

      addType: '', // same   under
      visible: false,
      showAdd: false,
      selectedNode: null,
      form: {
        departmentName: '',
        teamNumber: '',
        employerName: '',
        employeeName: '',
        contractNumber: '',
        contractName: '',
        projectName: '',
        initAmount: '',
        signTime: '',
        description: '',
        remark: '',
        elecContractUpload: '',
        paperContractUpload: '',
        addWorkflowId: '',
        status: '',
        founderName: '',
        founderUnit: '',
        createTime: ''
      },
      showAddDetailModal: false,
      selectRow: null,
      detailDataList: [],
      detailDataItem: {
      },
      columns: [
        {
          label: '编号',
          slot: 'number'
        },
        {
          label: '名称',
          slot: 'name'
        },
        {
          label: '单位',
          slot: 'unit'
        },
        {
          label: '税率',
          slot: 'taxRate',
          width: '150'
        },
        {
          label: '税金',
          slot: 'taxes',
          width: '150'
        },
        {
          label: '单价',
          slot: 'unitPrice'
        },
        {
          label: '数量',
          slot: 'count'
        },
        {
          label: '合价',
          slot: 'sumPrice'
        },
        {
          label: '描述',
          slot: 'description'
        },
        {
          label: '备注',
          slot: 'remark'
        }
      ],
      showTargetSetListModal: false,
      showTeamListModal: false,
      fileList: [
      ],
      rules: {
        name: [
          { required: true, message: '单位名称', trigger: 'change' }
        ],
        unifiedSocialCreditCode: [
          { required: true, message: '统一社会信用代码', trigger: 'change' }
        ]
      },
      provinceData: [],
      cityData: []
    }
  },
  computed: {
    disableForm() {
      return this.optType === 'detail'
    },
    show: {
      get() {
        return this.showModal
      },
      set(val) {
        this.$emit('update:showModal', val)
      }
    }
  },
  watch: {
    showModal(val) {
      if (val && this.optType !== 'add') {
        this.getDocDetail(this.data.id)
        this.$nextTick(() => {
          Object.keys(this.form).forEach(key => {
            const source = this.data[key]
            if (typeof source === 'boolean') {
              this.form[key] = source ? 1 : 0
            } else {
              this.form[key] = source
            }
          })
        })
      } else if (!val) {
        this.fileList = []
        this.detailDataList = []
        this.$refs.form.resetFields()
      }
    }
  },
  mounted() {
    this.getRegionData()
  },
  methods: {
    /**
     * 验证清单编号:
     * 1、清单编号不能为空
     * 2、清单编号不能重复
     */
    validChecklistNumber() {
      const data = this.detailDataList

      if (data.find(item => item.number.length === 0)) {
        this.$message.warning('清单编号不能为空！')
        return false
      }

      const source = data.map(item => { return item.number })
      const target = [...new Set(source)]

      if (source.length !== target.length) {
        this.$message.warning('清单编号不能重复！')
        return false
      }

      return true
    },
    addRow() {
      this.detailDataList = [
        ...this.detailDataList,
        {
          number: '',
          name: '',
          unit: '',
          unitPrice: '',
          sumPrice: '',
          count: '',
          description: '',
          remark: ''
        }
      ]
    },
    getSelectedRowsTeam(obj) {
      this.form.initAmount = obj.basBidAmount
      this.form.employeeName = obj.supplierInfoName
      this.form.teamNumber = obj.bidNumber
    },
    getSelectedRows(obj) {
      this.form.projectName = obj.row.projName
    },
    addDetail() {
      this.$refs.detailForm.validate((valid) => {
        if (valid) {
          const item = JSON.parse(JSON.stringify(this.detailDataItem))
          this.detailDataList.push(item)
          this.showAddDetailModal = false
          this.$refs.detailForm.resetFields()
        }
      })
    },
    cancelAddDetail() {
      this.showAddDetailModal = false
    },
    delDetailDataItem() {
      if (this.selectRow) {
        const index = this.detailDataList.indexOf(this.selectRow)
        this.detailDataList.splice(index, 1)
      }
    },
    provinceChange(e) {
      const selectedData = this.provinceData.filter(val => val.name === e)[0]
      if (selectedData) {
        this.form.city = ''
        const params = {
          parentCode: selectedData.code,
          areaType: 2
        }
        getAreaList(params).then(res => {
          this.cityData = res.data || []
        })
      }
    },
    getDocDetail(id) {
      getTransferContractInfoDetail({ laborContractInfoId: id }).then(res => {
        const { lstAttachment, lstLaborContractChecklist } = res.data || {}
        if (lstAttachment && lstAttachment.length > 0) {
          this.fileList = lstAttachment
        }
        if (lstLaborContractChecklist && lstLaborContractChecklist.length > 0) {
          this.detailDataList = lstLaborContractChecklist
        }
      })
    },
    getRegionData() {
      getAreaList({ areaType: '1' }).then(res => {
        this.provinceData = res.data || []
      })
    },
    deleteDetail() {
    },
    saveDoc() {
      if (this.optType === 'detai') {
        this.show = false
        return
      }
      this.$refs.form.validate((valid) => {
        if (valid) {
          const validChecklist = this.validChecklistNumber()
          if (!validChecklist) {
            return
          }
          const params = {
            laborContractInfo: {
              ...this.form,
              ...this.optType === 'edit' ? {
                id: this.data.id
              } : {}
            },
            lstLaborContractChecklist: this.detailDataList.map(item => {
              return {
                ...item,
                ...this.optType === 'edit' ? {
                  laborContractInfoId: this.data.id
                } : {}
              }
            }),
            lstAttachment: this.fileList
          }
          const fn = this.optType === 'add' ? addTransferContractInfo : updateTransferContractInfo
          fn(params).then(res => {
            if (res.code === '0001') {
              this.$message({
                type: 'success',
                message: '保存成功!'
              })
              this.show = false
              this.$emit('freshList')
              this.$refs.form.resetFields()
            } else {
              this.$message({
                type: 'error',
                message: res.msg
              })
            }
          })
        }
      })
    },

    inputDconUnitPrice() {
      if (this.detailDataItem.unitPrice && this.detailDataItem.count) {
        this.detailDataItem.sumPrice = Number.parseFloat(this.detailDataItem.unitPrice) * Number.parseFloat(this.detailDataItem.count)
        this.detailDataItem.sumPrice = Number.parseFloat(this.detailDataItem.sumPrice).toFixed(2)
      } else {
        this.detailDataItem.sumPrice = ''
      }
    },
    inputDcount() {
      if (this.detailDataItem.unitPrice && this.detailDataItem.count) {
        this.detailDataItem.sumPrice = Number.parseFloat(this.detailDataItem.unitPrice) * Number.parseFloat(this.detailDataItem.count)
        this.detailDataItem.sumPrice = Number.parseFloat(this.detailDataItem.sumPrice).toFixed(2)
      } else {
        this.detailDataItem.sumPrice = ''
      }
    },
    inputUnitPrice() {
      this.detailDataList.forEach((item, index) => {
        if (item.unitPrice && item.count) {
          item.sumPrice = Number.parseFloat(item.unitPrice) * Number.parseFloat(item.count)
          item.sumPrice = Number.parseFloat(item.sumPrice).toFixed(2)
        } else {
          item.sumPrice = ''
        }
      })
    },
    inputCount() {
      this.detailDataList.forEach((item, index) => {
        if (item.unitPrice && item.count) {
          item.sumPrice = Number.parseFloat(item.unitPrice) * Number.parseFloat(item.count)
          item.sumPrice = Number.parseFloat(item.sumPrice).toFixed(2)
        } else {
          item.sumPrice = ''
        }
      })
    }

  }
}
</script>

<style lang="scss" scoped>
.com-form-title{
  font-size: 14px;
  font-weight: bold;
  line-height: 35px;
  color: #409EFF;
  border-bottom: 1px solid #dedede;
  margin-bottom: 6px;
}
</style>
